package com.heima.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IArticleService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ArticlePageDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IArticleService {
    private final ApArticleMapper articleMapper;
    private final ApArticleConfigMapper configMapper;
    private final ApArticleContentMapper contentMapper;


    @Override
    public List<ApArticle> getPage(Integer type, ArticlePageDto dto) {
        if (dto.getTag() != null && dto.getTag().equals("__dyna__")) {
            dto.setTag(null);
        }
        if (dto.getTag() != null && dto.getTag().equals("__all__")) {
            dto.setTag(null);
        }
        if (dto.getSize() > 100 || dto.getSize() < 0 || dto.getSize() == null) {
            dto.setSize(10);
        }
        List<ApArticle> page = articleMapper.getPage(type, dto);
        return page;
    }

    /**
     * 文章发布
     *
     * @param apArticleDto
     * @return
     */
    @Override
    public ApArticle saveArticle(ApArticleDto apArticleDto) {
        //1.新增文章
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(apArticleDto, apArticle);
        apArticle.setPublishTime(new Date());
        save(apArticle);
        //2.新增文章配置
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment((short) 1);
        apArticleConfig.setIsForward((short) 1);
        apArticleConfig.setIsDown((short) 0);
        apArticleConfig.setIsDelete((short) 0);
        configMapper.insert(apArticleConfig);
        //3.新增已发布文章内容
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(apArticleDto.getContent());
        contentMapper.insert(apArticleContent);
        return apArticle;
    }
}
